package com.vcredit.creditcat.activeMQ;

import com.vcredit.creditcat.enumtype.QueueNameEnum;
import com.vcredit.creditcat.util.EnumExtUtil;
import org.apache.activemq.command.ActiveMQDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.*;

/**
 * Created by liaoshengjun on 2017/10/26.
 */
@Service
public class CommonQueueListenerService implements MessageListener {
	@Autowired
	private QeueConsumerDoFactory qeueConsumerDoFactory;

	private static Logger logger = LoggerFactory.getLogger(CommonQueueListenerService.class);

	@Override
	public void onMessage(Message message) {
		try {
			ActiveMQDestination queues=(ActiveMQDestination)message.getJMSDestination();
			String queueName=queues.getPhysicalName();
			QueueNameEnum queueNameEnum =
					EnumExtUtil.getEnumOnValue(QueueNameEnum.class,
							queueName, "name");
			String dealClassName=queueNameEnum.getDealClass();
			// 如果是文本消息
			if (message instanceof TextMessage) {
				TextMessage tm = (TextMessage) message;
				try {
					logger.info("监听队列:"+queueName+"消费了消息:"+tm.getText());
					if(qeueConsumerDoFactory.exitClass(dealClassName)){
						IQueueConsumerDo consumerDo=qeueConsumerDoFactory.getQueueDealInterface(dealClassName);
						consumerDo.execute(tm.getText());
					}
				} catch (Exception e) {
					logger.error("消息队列处理出错！", e);
				}
			}
		} catch (Exception e){
			logger.error("消息队列监听出错！", e);
		}
	}
}
